package JavaNet;
import java.io.*;
import java.net.*;
/**
 * Created by lanouhn on 17/7/18.
 */
public class NetRequest {

    public static void main(String [] args)
    {
        HttpURLConnection connection = null;
        InputStream is =null;
        int code = 0;
        String myUrl = "http://cms-bucket.nosdn.127.net/d9d3131d3ab948f382978d437496b0c720170704105432.jpeg";
        String path = "/Users/lanouhn/Desktop/result.jpeg";

        try {
            URL url = new URL(myUrl);
            connection = (HttpURLConnection) url.openConnection();
            code = connection.getResponseCode();

            if(code == 200) {
                is = connection.getInputStream();

                File file = new File(path);
                outputBytes(is, file);

            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }finally {
            if(connection != null){
                connection.disconnect();
            }
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

//    工具类（未使用）：从输入流获取字节流写到文件
    public static void outputBytes(InputStream inStream, File file) throws IOException {
        FileOutputStream fos = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inStream.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        inStream.close();
    }

//    从输入流获取字符串输出到文件
    static void outputString(InputStream is, File file)throws IOException{
        BufferedReader br =
                new BufferedReader(new InputStreamReader(is));
        String line = "";
        StringBuilder sb = new StringBuilder();

        //读取输入流is到字符串
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        String result = sb.toString();

        //将字符串写到file文件
        FileWriter fw = new FileWriter(file);
        BufferedWriter writer = new BufferedWriter(fw);
        writer.write(result);
    }

}
